import { Button, Empty, Flex, InputNumber } from 'antd'
import { SetStateAction, useCallback, useEffect, useMemo, useState } from 'react'
import QuesDialog from './component/quesDialog'
import QuestionType from '@/component/common/questionType'
import './index.scss'
import MyInput from '@/component/common/myInput'
import PIcon from '@/component/common/pIcon'
import examApi from '../api/index'
import { useMessageApi } from '@/component/context/messageContext/message'
import { useLocation, useNavigate } from 'react-router-dom'
interface Ques {
  id: string
  name: string
  type: number
  answer: any
  data: Array<any>
  score: number
  title: string
}
interface QuesType {
  title: string
  sumScore: number
  ques: Array<Ques>
}
export interface ExamPaper {
  id?: string
  name: string
  content: Array<QuesType>
}
export default function AddExamPaper() {
  const navigate = useNavigate()
  const location = useLocation()
  const [selectionQues, setSelectionQues] = useState<Array<any>>([])
  const [isShowQuesDialog, setIsShowQuesDialog] = useState<boolean>(false)
  const [curAddQuesIndex, setCurAddQuesIndex] = useState<number>(0)
  const [examPaperData, setExamPaperData] = useState<ExamPaper>({
    id: '',
    name: '',
    content: [],
  })
  const messageApi = useMessageApi()

  const [isShowExamPaper, setIsShowExamPaper] = useState<boolean>(false)
  useEffect(() => {
    if (location.pathname.includes('show')) {
      setIsShowExamPaper(true)
      examApi.getPaper(location.pathname.split('/')[4]).then((data: any) => {
        setExamPaperData({
          id: data.id,
          name: data.name,
          content: data.content,
        })
        const quess: SetStateAction<any[]> = []
        data.content.map((item: any) => {
          return item.ques.map((ques: any) => {
            quess.push(ques)
            return ques
          })
        })
        setSelectionQues(quess)
      })
    }
  }, [location])

  const appendAndEditTestPaper = useCallback(() => {
    /**
     * 表单校验
     */
    if (!examPaperData.name) {
      messageApi.error('试卷名称不能为空')
      return
    }
    if (!examPaperData.content.length) {
      messageApi.error('请添加题型')
      return
    }
    for (let i = 0; i < examPaperData.content.length; i++) {
      if (!examPaperData.content[i].ques.length) {
        messageApi.error(`题型（内容）${examPaperData.content[i].title}为空`)
        return
      }
      if (!examPaperData.content[i].title) {
        messageApi.error(`题型（名称）${examPaperData.content[i].title}为空`)
        return
      }
      for (let j = 0; j < examPaperData.content[i].ques.length; j++) {
        if (!examPaperData.content[i].ques[j].score) {
          messageApi.error(
            `题目（分值）${examPaperData.content[i].ques[j].title.slice(
              0,
              5
            )}... 为空`
          )
          return
        }
      }
    }
    /**
     * 添加逻辑
     */
    if (!isShowExamPaper) {
      examApi.addTestPaper(examPaperData).then((data) => {
        messageApi.success('添加成功')
        setExamPaperData({
          name: '',
          content: [],
        })
        navigate(`/home/exampaper/show/${data}`)
      })
    } else {
      /**
       * 编辑逻辑
       */
      examApi.updateTestPaper(examPaperData).then(() => {
        messageApi.success('编辑成功')
      })
    }
  }, [examPaperData, isShowExamPaper, messageApi, navigate])
  // 试卷内容
  const ExamPaper = useMemo(() => {
    const removeQuestion = (itemIndex: number, index: number) => {
      let temp = examPaperData.content
      let removeTargetId = temp[itemIndex].ques[index].id
      temp[itemIndex].ques.splice(index, 1)
      setExamPaperData((oldV) => {
        return { ...oldV, content: temp }
      })
      setSelectionQues((oldV) => {
        let temp = [...oldV]
        temp.splice(
          temp.findIndex((item) => item.id === removeTargetId),
          1
        )
        return [...temp]
      })
    }
    return (
      <Flex vertical gap="2rem" className="exampaper">
        <MyInput
          className="exam-input"
          placeholder="请输入试卷名称"
          placeholdertext="请输入试卷名称"
          value={examPaperData.name}
          onChange={(e) => {
            setExamPaperData((oldV) => {
              return {
                ...oldV,
                name: e.target.value,
              }
            })
          }}></MyInput>
        {examPaperData.content?.length ? (
          examPaperData.content.map((item, itemIndex) => {
            return (
              <Flex
                vertical
                gap="1rem"
                key={itemIndex}
                className="exam-content"
                style={{ width: '80%' }}>
                <div className="type-name">
                  <MyInput
                    placeholder="请输入题型名称"
                    placeholdertext="请输入题型名称"
                    value={item.title}
                    onChange={(e) => {
                      setExamPaperData((oldV) => {
                        oldV.content[itemIndex].title = e.target.value
                        return {
                          ...oldV,
                        }
                      })
                    }}></MyInput>
                </div>
                <Flex gap="1rem" vertical>
                  {item.ques.length ? (
                    item.ques.map((ques, index) => {
                      return (
                        <Flex justify="space-between" key={index}>
                          <QuestionType
                            content={ques}
                            state="READ"></QuestionType>
                          <Flex>
                            <div className="score">
                              <InputNumber
                                placeholder="分值"
                                suffix="分"
                                min={0}
                                max={999}
                                value={ques.score}
                                onChange={(value) => {
                                  setExamPaperData((oldV) => {
                                    let temp = oldV.content
                                    temp[itemIndex].ques[index].score =
                                      value as number
                                    return {
                                      ...oldV,
                                      content: temp,
                                    }
                                  })
                                }}></InputNumber>
                            </div>
                            <Flex align="center">
                              <PIcon
                                name="icon-minus-circle"
                                onClick={() => {
                                  removeQuestion(itemIndex, index)
                                }}></PIcon>
                            </Flex>
                          </Flex>
                        </Flex>
                      )
                    })
                  ) : (
                    <Empty></Empty>
                  )}
                </Flex>
                <Flex justify="center">
                  <Button
                    color="default"
                    variant="dashed"
                    style={{ width: '10%' }}
                    onClick={() => {
                      setCurAddQuesIndex(itemIndex)
                      setIsShowQuesDialog(true)
                    }}>
                    添加题目
                  </Button>
                </Flex>
              </Flex>
            )
          })
        ) : (
          <Empty></Empty>
        )}
        <Flex className="panel" vertical gap="1rem">
          <Button
            color="default"
            variant="dashed"
            onClick={() => {
              const temp = examPaperData.content
              temp.push({
                title: '',
                sumScore: 0,
                ques: [],
              })
              setExamPaperData((oldv) => {
                return {
                  ...oldv,
                  content: temp,
                }
              })
            }}>
            添加板块
          </Button>
          <Button
            color="default"
            onClick={() => {
              appendAndEditTestPaper()
            }}>
            保存
          </Button>
        </Flex>
      </Flex>
    )
  }, [appendAndEditTestPaper, examPaperData.content, examPaperData.name])

  const Dialog = useMemo(() => {
    return (
      <QuesDialog
        destroyOnClose
        selectedQues={selectionQues}
        isOpen={isShowQuesDialog}
        onFinish={(selectedRows) => { 
          setSelectionQues(selectedRows)
          setIsShowQuesDialog(false)
          setExamPaperData((oldV) => {
            const temp = oldV.content
            let selectedIds = selectionQues.map((item) => {
              return item.id
            })
            let curSelectedIds = selectedRows.filter((item) => {
              return !selectedIds.includes(item.id)
            })
            temp[curAddQuesIndex].ques.push(...curSelectedIds)
            return {
              ...oldV,
              content: temp,
            }
          })
        }}
        onCancel={() => {
          setIsShowQuesDialog(false)
        }}></QuesDialog>
    )
  }, [curAddQuesIndex, isShowQuesDialog, selectionQues])

  return (
    <div>
      {ExamPaper}
      {Dialog}
    </div>
  )
}
